package com.bolehui.base.encrypt.encryptor;

import cn.hutool.core.codec.Base64;
import com.bolehui.base.annotation.SensitiveField;
import com.bolehui.base.encrypt.Decrypt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author chendongjie     email:chendongjie@gz.iscas.ac.cn
 * @version 1.0
 * @ClassName AESDecryptor
 * @Description
 * @createTime 2024/12/2 13:58
 * Copyright (C) 2021-2022 CASEEDER, All Rights Reserved.
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 */
@Component
public class Base64Decrypt implements Decrypt {


    @Value("${key_sensitive: SENSITIVE}")
    private String KEY_SENSITIVE;

    @Override
    public <T> T decrypt(T result) throws Exception {
        Class<?> resultClass = result.getClass();
        Field[] declaredFields = resultClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            //去除所有被EncryptDecryptFiled注解的字段
            SensitiveField sensitiveFiled = declaredField.getAnnotation(SensitiveField.class);
            if (!Objects.isNull(sensitiveFiled)) {
                //将此对象的 accessible 标志设置为指示的布尔值。值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。
                declaredField.setAccessible(true);
                //这里的result就相当于是字段的访问器
                Object object = declaredField.get(result);
                //只支持String解密
                if (object instanceof String) {
                    String value = (String) object;
                    //修改：没有标识则不解密
                    if(value.startsWith(KEY_SENSITIVE)) {
                        value = value.substring(10);
                        value = Base64.decodeStr(value, StandardCharsets.UTF_8);
                    }
                    //对注解在这段进行逐一解密
                    declaredField.set(result, value);
                }
            }
        }

        return result;
    }
}
